package wetalk.software.bupt.com.wetalk.view.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.jyt.message.Message;
import com.jyt.util.MySerializable;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import wetalk.software.bupt.com.wetalk.R;
import wetalk.software.bupt.com.wetalk.application.ChatManager;
import wetalk.software.bupt.com.wetalk.communicate.AndroidClientService;
import wetalk.software.bupt.com.wetalk.listener.PushListener;
import wetalk.software.bupt.com.wetalk.model.OnLoginListener;
import wetalk.software.bupt.com.wetalk.model.po.User;
import wetalk.software.bupt.com.wetalk.model.po.WeTalkUser;
import wetalk.software.bupt.com.wetalk.util.SharePreferenceUtil;
import wetalk.software.bupt.com.wetalk.util.WeTalkConfig;
import wetalk.software.bupt.com.wetalk.view.dialog.CustomDialog;

public class LoginActivity extends BaseActivity  {

    public static final String tag="LoginActivity";

    private AndroidClientService.SendBinder sendBinder;

    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            sendBinder= (AndroidClientService.SendBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

    EditText et_account,et_password;
    Button btn_login;
    TextView tv_forgetpassword;
    private SharedPreferences.Editor editor;
    private SharePreferenceUtil sharePreferenceUtil;
    private LoginBroadcastReceiver receiver;
    private OnLoginListener listener= new OnLoginListener(){
        @Override
        public void loginSuccess(User user) {
            Toast.makeText(LoginActivity.this,"用户" + user.getUserName()  + "登录成功",Toast.LENGTH_SHORT).show();
        }

        @Override
        public void loginFail(User user) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(LoginActivity.this);
            dialog.setTitle("警告");
            dialog.setMessage("登录失败\n密码或账号不正确");
            dialog.setCancelable(false);
            dialog.setPositiveButton("OK",new DialogInterface.OnClickListener(){

                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            dialog.show();
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //初始化控件
        initView();


        sharePreferenceUtil=new SharePreferenceUtil(this,"WeTalk_SP");
        String isLogin=sharePreferenceUtil.getValue("isLogin");

        if(isLogin.equals("yes")){
            Intent intent=new Intent(LoginActivity.this,MainActivity.class);
            startActivity(intent);
            finish();
        }
        System.out.println("执行了onCreate");
    }

    @Override
    protected void onStart() {
        super.onStart();
        //初始化事件
        event();
        //初始化广播接收器
        //initNewMessageBroadCast();
        String uniqueID="";
        sharePreferenceUtil=new SharePreferenceUtil(this,"WeTalk_SP");
        if (!sharePreferenceUtil.getValue("uniqueID").equals("")){
            uniqueID = sharePreferenceUtil.getValue("uniqueID");
        }else{
            //只在第一次生成uuid和wetalkLogin的user
            uniqueID = UUID.randomUUID().toString();
            User user=new User(uniqueID,"WeTalkLogin","","","","","");
            SharePreferenceUtil sp = new SharePreferenceUtil(this, "WeTalk_SP");
            sp.saveObject(user, "user");
        }
        sharePreferenceUtil.saveValue(uniqueID,"uniqueID");
        Intent startIntent = new Intent(this, AndroidClientService.class);
        startIntent.putExtra("userID",uniqueID);
        startService(startIntent);
        Intent bindIntent = new Intent(this, AndroidClientService.class);
        bindService(bindIntent, connection, BIND_AUTO_CREATE);
        System.out.println("绑定服务成功");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        System.out.println("onRestart执行了");
    }

    /*
       初始化广播接收器
     */
    private void initNewMessageBroadCast(){
        // 注册接收消息广播
        receiver = new LoginBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(WeTalkConfig.BROADCAST_USER_LOGIN);
        registerReceiver(receiver, intentFilter);
        System.out.println("注册接收器成功");
    }

    public void initView(){
        et_account = (EditText) findViewById(R.id.et_username);
        et_password = (EditText)findViewById(R.id.et_password);
        btn_login = (Button)findViewById(R.id.btn_login);
        tv_forgetpassword = (TextView) findViewById(R.id.btn_forgetpass);
    }

    //事件响应
    private void event(){
        /*
        登陆事件响应
         */
        btn_login.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                String name = et_account.getText().toString().trim();
                String password = et_password.getText().toString().trim();

                Pattern pattern_name = Pattern.compile("^([a-zA-Z0-9]{8,12})");
                Matcher matcher_name = pattern_name.matcher(name);

                if (name.isEmpty() || password.isEmpty()) {
                    AlertDialog.Builder dialog = new AlertDialog.Builder(LoginActivity.this);
                    dialog.setTitle("警告");
                    dialog.setMessage("用户名或密码不能为空请重试");
                    dialog.setCancelable(false);
                    dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
                    dialog.show();
                }else if(!matcher_name.matches()){
                    Toast.makeText(LoginActivity.this,"用户名为6-12位数字或大小写字母",Toast.LENGTH_SHORT).show();
                }else{
                    CustomDialog.getDialog(LoginActivity.this,"正在登录...").show();
                    login(name,password);
                    initNewMessageBroadCast();
                }
            }

        });

        /*
         *忘记密码事件响应
         */
        tv_forgetpassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder dialog = new AlertDialog.Builder(LoginActivity.this);
                dialog.setTitle("忘记密码？");
                dialog.setMessage("请联系管理员：\n电话：13700011212\n邮箱：fhsdakhfk@163.com");
                dialog.setCancelable(false);
                dialog.setPositiveButton("OK",new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
                dialog.show();
            }
        });
    }

    private void login(final String name, final String password)  {
        final SharePreferenceUtil sharePreferenceUtil=new SharePreferenceUtil(this,"WeTalk_SP");
        sharePreferenceUtil.saveValue(password,"password");
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject json = new JSONObject();
                try {
                    json.put(WeTalkUser.PUSH_KEY_USERNAME,name);
                    json.put(WeTalkUser.PUSH_KEY_PASSWORD,password);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                byte[] bs;
                bs = MySerializable.object_bytes(json.toString());
                String uniqueID=sharePreferenceUtil.getValue("uniqueID");
                Message login = new Message(uniqueID,"sys_login","login",bs);

                Log.d(tag,"登陆信息-->"+login.toString());
                if (sendBinder!=null) {
                    sendBinder.sendMessage(login);
                    Log.d(tag,"登录信息发送成功");
                } else {
                    Log.d(tag,"登录信息发送失败");
                }
            }
        });
        thread.start();
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.out.println("onDestroy执行了");
        ChatManager.getInstance(this).unBindService();
    }

    private class LoginBroadcastReceiver extends BroadcastReceiver {
        User user;
        @Override
        public void onReceive(final Context context, Intent intent) {
            unbindService(connection);
            System.out.println("解绑服务成功");
            unregisterReceiver(receiver);
            System.out.println("取消接收器成功");
            CustomDialog.getDialog(LoginActivity.this,"正在登陆...").close();
            String str = intent.getStringExtra("result");
            String result=null;
            String id = null;
            String department = null;
            String email = null;
            String phone = null;
            String avatar = null;
            String name = null;
            try {
                JSONObject jsonObject=new JSONObject(str);
                result=jsonObject.getString("success");
                id = jsonObject.getString("uid");
                name = jsonObject.getString("uname");
                department = jsonObject.getString("udepartment");
                email = jsonObject.getString("uemail");
                phone = jsonObject.getString("uphone");
            } catch (JSONException e) {
                e.printStackTrace();
            }

            if(result.equals("yes")){

                user = new User(id,name,null,avatar,department,phone,email);

                SharePreferenceUtil sharePreferenceUtil = new SharePreferenceUtil(context, "WeTalk_SP");
                sharePreferenceUtil.saveObject(user, "user");
                sharePreferenceUtil.saveValue("yes","isLogin");


                listener.loginSuccess(user);
                userManager.closeAndroidClient(new PushListener() {
                    @Override
                    public void onSuccess() {
                        Intent intent1 = new Intent(context, MainActivity.class);
                        context.startActivity(intent1);
                        //context.unregisterReceiver(receiver);
                    }

                    @Override
                    public void onFailure(int var1, String var2) {

                    }
                });

            }else{
                listener.loginFail(user);
            }
        }
    }

}
